<?php


namespace app\user\controller;


use think\Controller;
use app\user\model\Student as studentmodel;
use app\user\model\Expert as expertmodel;
use think\facade\Request;
use think\facade\Session;

class Login extends Controller
{

    public function login()
    {
        return view("login");
    }

    //盐值加密函数
    public function salt($pwd)
    {
        $salt  = "ssjxyz";  //定义一个salt值，程序员规定下来的随机字符串
        $spwd  = $pwd . $salt;  //把密码和salt连接
        $mspwd = md5($spwd);  //执行MD5散列
        return $mspwd;  //返回散列
    }

    public function logincheck()
    {
        $status = 0;
        if (Request::isAjax()) {
            $data      = Request::post();
            $password  = $data['password'];
            $name      = $data['name'];
            $type      = $data['type'];
            $salt      = $this->salt($password);
            $mpassword = md5($password);
//            学生
            if ($type == 1) {
                $student = studentmodel::where('id', '=', $name)->find();
                if ($student) {
                    if (($student['pwd'] == $mpassword) && ($student['salt'] == $salt)) {
                        $status      = 1;
                        $sessionname = $student['name'];
                        $sessionid   = $student['id'];
                        Session::set('studentname', $sessionname);
                        Session::set('studentid', $sessionid);
                        //初始密码
                        $initpwd  = md5('123456');
                        $sinitpwd = $this->salt('123456');
                        if ($initpwd == $mpassword && $sinitpwd == $salt) {
                            $status = 5;
                        }
                    } else {
                        $status = 3;
                    }
                } else {
                    $status = 4;
                }
            } //教师
            else {
                $expert = expertmodel::where('id', '=', $name)->find();
                if ($expert) {
                    if (($expert['pwd'] == $mpassword) && ($expert['salt'] == $salt)) {
                        $status = 2;
                        Session::set('expertname', $name);
                        $status      = 6;
                        $sessionname = $expert['name'];
                        $sessionid   = $expert['id'];
                        Session::set('expertname', $sessionname);
                        Session::set('expertid', $sessionid);
                        //初始密码
                        $initpwd  = md5('123456');
                        $sinitpwd = $this->salt('123456');
                        if ($initpwd == $mpassword && $sinitpwd == $salt) {
                            $status = 7;
                        }
                    } else {
                        $status = 3;
                    }
                } else {
                    $status = 4;
                }
            }
        }
        return $status;
    }

}